package SGEngine

import (
	"github.com/gl"
)

type ICamera interface {
	RenderLayer() uint32
	SetRenderLayer(uint32)

	SetCamera()
	SetScene(*Scene)

	RenderNodes(INode)
}

//////////////////////////////
///BaseCamera
//////////////////////////////
type BaseCamera struct {
	CamScene *Scene
	Layer    uint32
}

func (c *BaseCamera) SetScene(scene *Scene) {
	c.CamScene = scene
}

func (c *BaseCamera) RenderLayer() uint32 {
	return c.Layer
}

func (c *BaseCamera) SetRenderLayer(layer uint32) {
	c.Layer = layer
}

//////////////////////////////
///Camera2D
//////////////////////////////
type Camera2D struct {
	BaseCamera
}

func NewCamera2D() ICamera {
	RCam := new(Camera2D)
	return RCam
}

func (Cam *Camera2D) RenderNodes(PNode INode) {
	gl.MatrixMode(gl.MODELVIEW)
	if Cam.RenderLayer()&PNode.GetLayer() > 0 || PNode.GetLayer() == 0 && PNode.GetNode().Enable == true {
		gl.PushMatrix()
		PNode.GetTransfrom().TransfromNode()
		if PNode.GetRender() != nil {
			PNode.GetRender().Render()
		}
		PNode.GetTransfrom().EndTransfromNode()
		C := *PNode.Childrens()
		//Sort(C.ArrData, 0, C.GetSize()-1)
		for i := 0; i < C.GetSize(); i++ {
			Cam.RenderNodes(C.I(i).(INode))
		}
		gl.PopMatrix()
	}
}

func (c *Camera2D) SetCamera() {
	gl.MatrixMode(gl.PROJECTION)
	gl.LoadIdentity()
	gl.Ortho(float64(-c.CamScene.Size().X*0.5), float64(c.CamScene.Size().X*0.5),
		float64(-c.CamScene.Size().Y*0.5), float64(c.CamScene.Size().Y*0.5), -10.0, 10)
	gl.Enable(gl.DEPTH_TEST)
	gl.DepthFunc(gl.LEQUAL)

	gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
	gl.ClearColor(gl.GLclampf(c.CamScene.BgColor.R), gl.GLclampf(c.CamScene.BgColor.G), gl.GLclampf(c.CamScene.BgColor.B), 1)
	gl.ClearDepth(1)
}
